package org.zjx.core.monitor;

import org.zjx.core.DecisionNode;
import org.zjx.core.nodes.*;

public class TextDecisionTreeVisualizer implements DecisionTreeVisualizer {
    @Override
    public String visualize(DecisionNode root) {
        StringBuilder sb = new StringBuilder();
        visualizeSubTree(root, 0, sb);
        return sb.toString();
    }

    private void visualizeSubTree(DecisionNode node, int depth, StringBuilder sb) {
        if (node == null) {
            return;
        }
        // 添加缩进
        for (int i = 0; i < depth; i++) {
            sb.append("  ");
        }
        // 添加节点ID
        sb.append(node.getNodeId()).append("\n");

        // 根据节点类型递归处理子节点
        if (node instanceof SequenceNode) {
            SequenceNode seqNode = (SequenceNode) node;
            for (DecisionNode child : seqNode.getNodes()) {
                visualizeSubTree(child, depth + 1, sb);
            }
        } else if (node instanceof ConditionNode) {
            ConditionNode condNode = (ConditionNode) node;
            // 打印条件节点
            sb.append("  ".repeat(depth)).append("  Condition\n");
            // 打印True分支
            visualizeSubTree(condNode.getTrueBranch(), depth + 1, sb);
            // 打印False分支
            visualizeSubTree(condNode.getFalseBranch(), depth + 1, sb);
        } else if (node instanceof ActionNode) {
            ActionNode actionNode = (ActionNode) node;
            // 打印Action节点
            sb.append("  ".repeat(depth)).append("  Action: ").append(actionNode.getAction().getActionId()).append("\n");
            // 打印下一个节点
            if (actionNode.getNext() != null) {
                visualizeSubTree(actionNode.getNext(), depth + 1, sb);
            }
        } else if (node instanceof ParallelNode) {
            ParallelNode parallelNode = (ParallelNode) node;
            sb.append("  ".repeat(depth)).append("  Parallel\n");
            for (DecisionNode child : parallelNode.getBranches()) {
                visualizeSubTree(child, depth + 1, sb);
            }
        } else if (node instanceof LoopNode) {
            LoopNode loopNode = (LoopNode) node;
            sb.append("  ".repeat(depth)).append("  Loop\n");
            visualizeSubTree(loopNode.getBody(), depth + 1, sb);
        }
        // 其他节点类型可以根据需要添加
    }
}